package com.jie.aop;

import com.alibaba.fastjson.JSON;
import com.jie.service.OperationLogService;
import com.jie.utils.IPUtils;
import com.jie.entity.OperationLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperationLogService operationLogService;
    @Pointcut("@annotation(com.jie.aop.OperationLogAnnotation)")
    public void OperLogPointCut(){

    }
    @AfterReturning("OperLogPointCut()")
    public void saveSysLog(JoinPoint joinPoint){
        OperationLog operationLog=new OperationLog();
        MethodSignature signature=(MethodSignature) joinPoint.getSignature();
        Method method=signature.getMethod();
        OperationLogAnnotation operationLogAnnotation=method.getAnnotation(OperationLogAnnotation.class);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        if(operationLogAnnotation!=null){
            String value=operationLogAnnotation.value();
            operationLog.setDescription(value);
        }
        String className=joinPoint.getTarget().getClass().getName();
        String methodName=method.getName();
        operationLog.setType(className+"."+methodName);
        Object[] args=joinPoint.getArgs();
        String model=JSON.toJSONString(args);
        operationLog.setModel(model);
        operationLog.setOperationTime(new Date());
//        String username = ((OperationLog) SecurityUtils.getSubject().getPrincipal()).getUserCode();
        operationLog.setUserCode(request.getHeader("userCode"));
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        operationLog.setIp(IPUtils.getRealIp(request));
        operationLogService.save(operationLog);
        }
}
